package com.miloyu.modelnet.network

import android.net.ParseException
import android.util.Log
import android.widget.Toast
import com.example.mvvm.base.data.SingleLiveEvent
import com.example.mvvm.rx.RxBus
import com.example.mvvm.until.Tips
import com.google.gson.JsonParseException
import com.google.gson.stream.MalformedJsonException
import com.miloyu.modelnet.BusEventInfo

import io.reactivex.observers.DisposableObserver
import org.json.JSONException
import retrofit2.HttpException
import java.lang.IndexOutOfBoundsException
import java.net.ConnectException
import java.net.SocketTimeoutException
import java.net.UnknownHostException
import java.util.concurrent.ConcurrentHashMap

/**
 * @Author: YY
 * @Time: 2021/8/12
 * @Describe 请求响应的处理
 */
abstract class ApiResponse<T> : DisposableObserver<BaseResponse<out T>>() {

    private val TAG: String = ApiResponse::class.java.simpleName

    abstract fun success(data: T?, msg: String?)
    abstract fun onFail(e: Throwable?, errorMsg: String?)


    override fun onStart() {
        super.onStart()
        Log.d(TAG, "onSubscribe")
    }

    override fun onNext(t: BaseResponse<out T>) {
        Log.d(TAG, "onNext")
        when (t.code) {
            0 -> {
                success(t.data, t.msg)
                return
            }
            403 -> {
                RxBus.getDefault().post(BusEventInfo(403))
                onFail(Exception(t.msg), t.msg)
            }
            else -> {
                onFail(Exception(t.msg), t.msg)
            }
        }
    }

    override fun onError(e: Throwable) {
        Log.d(TAG, "onError ${e.message}")

        val msg: String? = if (e is HttpException) {
            when (e.code()) {
                403 -> "403 请求被拒绝"
                404 -> "404 服务器无响应 "
                408 -> "408 服务器执行超时 "
                500 -> "500 服务器执行超时"
                503 -> "503 服务器不可用"
                else -> "网络错误"
            }
        } else if (e is SocketTimeoutException) {
            "连接超时"
        } else if (e is ConnectException) {
            "连接失败, 请检查网络"
        } else if (e is UnknownHostException) {
            "主机地址未知"
        } else if (e is JsonParseException
            || e is JSONException
            || e is ParseException
            || e is MalformedJsonException
        ) {
            "解析错误"
        } else if (e is IndexOutOfBoundsException) {
            "数组异常"
        } else {
            e.message
        }
        onFail(e, msg)
    }

    override fun onComplete() {
        Log.d(TAG, "onComplete")
    }

    fun onCache(){

    }
}